from django.http.response import HttpResponse
from django.shortcuts import render,reverse
# Create your views here.
from .models import ServerInfo
from django.http import HttpResponseRedirect
from django.shortcuts import redirect



def index(request):
    return render(request, 'index.html')

def show(request):
    # res_list = ServerInfo.objects.values('id','hostname','os','cpu','memory','ip')
    res_list = ServerInfo.objects.all()
    # context = {'title': '首页', 'res_list': res_list}
    return render(request, 'serverlist.html', context=locals())

# def addserver(request):
#     server1 = ServerInfo(hostname='hw-server2',os='Centos7',cpu='4c',memory='8G',ip='111.111.111.111')
#     server1.save()
#     return HttpResponse("<p>数据添加成功！</p>")

def add(request):
    return render(request, 'addserver.html')

def addone(request):
    if request.method == "POST":
        # 获取用户提交的数据 POST请求中
        hostname1 = request.POST.get('hostname')
        os1 = request.POST.get('os')
        cpu1 = request.POST.get('cpu')
        memory1 = request.POST.get('memory')
        ip1 = request.POST.get('ip')
        server1 = ServerInfo(hostname=hostname1,os=os1,cpu=cpu1,memory=memory1,ip=ip1)
        server1.save()
        # temp = {'username': u, 'email': e, "gender": g}
        # USER_LIST.append(temp)
    message = hostname1 + "记录添加成功！"
    # return render(request, 'addserver.html', context=locals())
    return redirect('/show')
def searchone(request):
    if request.method == "POST":
        kword = request.POST.get('kword')
        res_list = ServerInfo.objects.all().filter(hostname=kword)
    return render(request, 'oneserver.html', context=locals())

# def todelete(request):
#     return render(request, 'deleteone.html', context=locals())

def deletebyid(request,id):
    ServerInfo.objects.filter(id=id).delete()
    res_list = ServerInfo.objects.all()
    script="alert"
    message="记录已删除!"
    return redirect('/show')
    # return render(request,'serverlist.html',context=locals())
    # return HttpResponse(id+"记录已删除")
    # return HttpResponse('<script>alert("'+id+'记录已删除!");</script>')

def toupdate(request,id):
    res_all=ServerInfo.objects.all().filter(id=id)
    res_list=res_all[0]
    return render(request,'updateserver.html',context=locals())

def updatebyid(request,id):
    if request.method == "POST":
        hostname1 = request.POST.get('hostname')
        os1 = request.POST.get('os')
        cpu1 = request.POST.get('cpu')
        memory1 = request.POST.get('memory')
        ip1 = request.POST.get('ip')
        ServerInfo.objects.filter(id=id).update(hostname=hostname1,os=os1,cpu=cpu1,memory=memory1,ip=ip1)
    return redirect('/show')

def deleteone(request):
    if request.method == "POST":
        kword = request.POST.get('kword')
        ServerInfo.objects.filter(hostname=kword).delete()
    message=kword+"记录删除成功！"
    return render(request, 'deleteone.html', context=locals())

def advance(request):
    return render(request, 'advance.html')